<template>
  <div :class="wrpCls">
    <!-- 用户工具栏插槽 -->
    <div class="x-user-bar">
      <!-- 代理返回 -->
      <a-dropdown v-if="ownerToken"
                  placement="bottomRight">
        <!-- 头像 -->
        <span class="header-userinfo"
              title="返回主帐号">
          <a-icon type="home"
                  @click="handleReturnAgenClick" />
        </span>
      </a-dropdown>

      <!-- 代理切换 -->
      <a-dropdown v-if="agentList && agentList.length>0 && !ownerToken"
                  placement="bottomRight">
        <!-- 头像 -->
        <span class="header-userinfo"
              title="代理">
          <a-icon type="user" />
          <!-- <a-avatar
            size="small"
            icon="user"
            class="antd-pro-global-header-index-avatar" />
          <span style="display:inline-block;font-size: var(--font-size-def);font-weight: bold;">代</span> -->
        </span>
        <template #overlay>
          <a-menu :visible="true">
            <!-- 代理帐号 -->
            <a-sub-menu>
              <span slot="title">
                <a-icon type="swap" />
                代理帐号&nbsp;
              </span>
              <a-menu-item v-for="(item, index) in agentList"
                           :key="index">
                <div @click="handleAgenClick(index, item)"
                     :class="item.selected ? 'x-user-menu-unit-active' : ''">
                  {{ item.name }}
                  <a-icon v-if="item.selected"
                          type="check" />
                </div>
              </a-menu-item>
            </a-sub-menu>

            <a-menu-divider />
          </a-menu>
        </template>
      </a-dropdown>

      <slot name="toolbar" />
      <MessageIcon :style="{'color': $store.getTheme('navTheme')=='dark' && $store.getTheme('navPosition')==='top'?'#fff':undefined}"
                   v-if="!$slots.toolbar" />
      <!-- 帮助图标 -->
      <div v-if="$store.getAppConfig('_helper')!==false">
        <slot name="help" />
        <a-icon v-if="!$slots.help"
                type="question-circle"
                :style="{'color': $store.getTheme('navTheme')=='dark' && $store.getTheme('navPosition')==='top'?'#fff':undefined}"
                @click="onHelpClick" />
      </div>
    </div>

    <!-- 用户信息 -->
    <a-dropdown v-if="!$slots.user && fullName"
                placement="bottomRight">
      <!-- 头像 -->
      <span class="header-userinfo">
        <a-avatar v-if="avatar"
                  size="small"
                  :src="avatar"
                  class="antd-pro-global-header-index-avatar" />
        <a-avatar v-else
                  size="small"
                  icon="user"
                  class="antd-pro-global-header-index-avatar" />
        <span :style="{
          'display':'inline-block',
          'padding-left': '10px',
          'color': $store.getTheme('navTheme')=='dark' && $store.getTheme('navPosition')==='top'?'#fff':undefined
        }">
          {{ fullName }}
        </span>
      </span>
      <template #overlay>
        <a-menu :visible="true">
          <!-- 工作单位 -->
          <a-sub-menu v-if="unitList && unitList.length>0">
            <span slot="title">
              <a-icon type="deployment-unit" />
              工作单位&nbsp;
            </span>
            <a-menu-item v-for="(item, index) in unitList"
                         :key="index">
              <div @click="handleUnitClick(index, item)"
                   :class="item.selected ? 'x-user-menu-unit-active' : ''">
                {{ item.name }}
                <a-icon v-if="item.selected"
                        type="check" />
              </div>
            </a-menu-item>
          </a-sub-menu>

          <a-menu-item v-if="Object.keys($store.getThemes()||{}).length>0"
                       @click="()=>$emit('themeSetting')">
            <a-icon type="profile" />
            个性化设置
          </a-menu-item>

          <a-menu-item @click="handlePassword">
            <a-icon type="lock" />
            修改密码
          </a-menu-item>

          <a-menu-divider />
          <a-menu-item key="logout"
                       @click="handleLogout">
            <a-icon type="logout" />
            退出登录
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>

    <!-- 修改密码弹窗 -->
    <a-modal title="修改密码"
             :centered="true"
             :maskClosable="false"
             :visible="password.visible"
             :confirmLoading="password.loading"
             @ok="handleChangePassword"
             @cancel="password.visible=false">
      <a-form-model :model="password.form"
                    ref="form"
                    :label-col="{ span: 5 }"
                    :wrapper-col="{ span: 18 }"
                    :rules="{
                      oldPass: [{required: true, message: '此项为必填项'}],
                      newPass: [{validator: validatePass, trigger: 'blur'},{required: true, message: '此项为必填项'}],
                      mpassword: [{validator: validatePass, trigger: 'blur'},{required: true, message: '此项为必填项'}]
                    }">
        <a-form-model-item label="原密码"
                           prop="oldPass">
          <a-input v-model.trim="password.form.oldPass"
                   type="password" />
        </a-form-model-item>
        <a-form-model-item label="新密码"
                           prop="newPass">
          <a-input v-model.trim="password.form.newPass"
                   type="password" />
        </a-form-model-item>
        <a-form-model-item label="确认密码"
                           prop="mpassword">
          <a-input v-model.trim="password.form.mpassword"
                   type="password" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 个性化主题设置 -->
    <!-- <ThemesSetting ref="themeSettingForm" /> -->
  </div>
</template>

<script>
// 1、引入Vue等框架组件库或插件
// 2、引入自定义组件
// 3、引入第三方工具类插件
// 4、引入自定义工具或插件或混入或基类等
import PropType from '@zh/common-utils/prop-types'
// 5、引入API
import { changeLoginUnit, changeLoginAgent, logout } from '../api/auth/index'
import storage from '@zh/common-utils/utils/storage'
import { changePassword } from '../api/user/index'

import { getCurrentUserUnitGroupAndLines, getparentUnits } from '../api/unit/group'
import MessageIcon from '../components/MessageIcon'

export default {
  components: { MessageIcon },
  props: {
    fullName: PropType.string.require(),
    avatar: PropType.string.def(''),
    unitList: PropType.array.def([]),
    agentList: PropType.array.def([])
  },
  data () {
    return {
      ownerToken: null,
      password: {
        form: {},
        loading: false,
        visible: false
      }
    }
  },
  computed: {
    wrpCls () {
      return {
        'ant-pro-global-header-index-right': true
        // [`ant-pro-global-header-index-${this.isMobile || !this.topMenu ? 'light' : this.theme}`]: true
        // [`ant-pro-global-header-index-${ ? 'light' : this.theme}`]: true
      }
    }
  },
  created () {
    this.ownerToken = this.storage?.getOwnerToken()
    this.loadUnitGroup()
  },
  methods: {
    loadUnitGroup () {
      if (this.$store.state?.unitgroups.unitGroupList.length == 0 || this.$store.state?.businesslines.businessLineList.length == 0) {
        getCurrentUserUnitGroupAndLines().then(res => {
          this.$store.commit('unitgroups/SET_UNIT_GROUP_LIST', res.unitgroup)
          this.$store.commit('businesslines/SET_BUSINESS_LINE_LIST', res.businessline)
        })
      }
      if (this.$store.state?.parentUnits.parentUnitList.length === 0) {
        const unitIds = this.unitList.map(item => item.deptId)
        getparentUnits(unitIds).then(res => {
          this.$store.commit('parentUnits/SET_PARENT_UNIT_LIST', res)
        })
      }
    },
    reloadUnitGroupAndLine () {
      this.$store.commit('unitgroups/SET_UNIT_GROUP_LIST', [])
      this.$store.commit('businesslines/SET_BUSINESS_LINE_LIST', [])
      this.$store.commit('parentUnits/SET_PARENT_UNIT_LIST', [])
    },
    handlePassword () {
      this.password.visible = true
      this.password.form = {}
      this.password.loading = false
    },
    handleChangePassword () {
      this.$refs.form.validate((ok) => {
        if (!ok) {
          return
        }
        if (this.password.form.newPass != this.password.form.mpassword) {
          this.message.error('确认密码与新密码不一致')
          return
        }
        this.password.loading = true
        changePassword(this.password.form)
          .then((response) => {
            this.password.visible = false
            this.$router.redirectLogin(this.$route.fullpath)
          })
          .finally(() => {
            this.password.loading = false
          })
      })
    },
    handleReturnAgenClick () {
      storage.setToken(storage.getOwnerToken().value, storage.getOwnerToken().expired)
      storage.removeOwnerToken()
      location.replace('/')
    },
    /**
     * 切换代理用户
     */
    handleAgenClick (index, item) {
      if (this.agentList[index].selected) {
        return
      }
      this.agentList.map((agent) => {
        agent.selected = false
      })
      const agent = this.agentList[index]
      let param = {
        principalBy: agent.agentId,
        agentBy: this.$store.getLoginUser().unitUserId,
        type: 2
      }
      storage.setOwnerToken(storage.getToken().value, storage.getToken().expired)
      changeLoginAgent(param).then((response) => {
        storage.setToken(response.token, response.validTime)
        location.replace('/')
      })
    },
    /**
     * 切换登录单位
     */
    handleUnitClick (index, item) {
      if (this.unitList[index].selected) {
        return
      }
      this.unitList.map((unit) => {
        unit.selected = false
      })
      const unit = this.unitList[index]
      changeLoginUnit(unit.unitUserId).then((response) => {
        this.reloadUnitGroupAndLine()
        location.replace('/')
      })
    },
    handleLogout () {
      const me = this
      this.confirm({
        title: '提示',
        content: '确认退出登录?',
        okText: '确认',
        cancelText: '取消',
        onOk () {
          logout().finally(() => {
            storage.removeOwnerToken()
            me.$router.redirectLogin('/')
          })
        },
        onCancel () { }
      })
    },
    validatePass () {
      return true
    },
    onHelpClick () {
      this.$helper({
        parentVM: this
      })
    }
  }
}
</script>

<style lang="less" scoped>
.header-userinfo {
  display: inline-block;
  padding: 0px 8px;
  vertical-align: top;
  &:hover {
    background: #00000014;
  }
}
.x-user-bar {
  display: inline-block;
  > * {
    display: inline-block;
    height: 100%;
    box-sizing: border-box;
    padding: 0 8px;
    font-size: 18px;
    cursor: pointer;
  }
  ::v-deep .ant-badge {
    font-size: 18px;
  }
}
</style>